package com.mmx.baseservice.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mmx.baseservice.admin.mapper.AdInfoMapper;
import com.mmx.baseservice.admin.pojo.AdInfo;
import com.mmx.baseservice.common.config.KeyConfig;
import com.mmx.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.mmx.baseservice.common.security.config.SecurityConfig;
import com.mmx.baseservice.common.security.jwt.JwtTokenUtil;
import com.mmx.baseservice.common.utils.CommUtil;
import com.mmx.baseservice.common.utils.returnbody.ReturnBody;
import com.mmx.baseservice.user.mapper.UsInfoMapper;
import com.mmx.baseservice.user.pojo.UsInfo;
import com.mmx.baseservice.user.service.UsInfoService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author mmx generator
 * @since 2021-07-23
 */
@Service
public class UsInfoServiceImpl extends CommonServiceImpl<UsInfoMapper, UsInfo> implements UsInfoService {

    @Resource
    private AdInfoMapper adInfoMapper;
    @Resource
    private AuthenticationManager authenticationManager;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(String phone) {
//        new UsInfo().setAddress()
    }

    @Override
    public String authority(UsInfo usInfo) {
        if (!CommUtil.checkNull(usInfo)) {
            return ReturnBody.error("用户不存在");
        }
        if (!CommUtil.checkNull(usInfo.getAdId())){
            return ReturnBody.error("账号审核未通过，请耐心等待");
        }
        //冻结该用户管理员账号，用户端也不可登录
        AdInfo adInfo = adInfoMapper.selectOneForUpdate(new QueryWrapper<AdInfo>().eq(AdInfo.ID, usInfo.getAdId()));
        if (!CommUtil.checkNull(adInfo)||adInfo.getStatus()!=0){
            return ReturnBody.error("账号已被冻结请联系管理员解冻");
        }
        // 用户认证
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(usInfo.getPhone() + SecurityConfig.ROLE_USER, usInfo.getPassword() + KeyConfig.KEY_PWD);
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        JSONObject jsonObject = new JSONObject();
        // 秘钥
        jsonObject.put("token", "Bearer_" + JwtTokenUtil.generateToken((UserDetails) authentication.getPrincipal(), 7200));
        return ReturnBody.success(jsonObject);
    }
}
